package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.exception.DeleteDishException;
import com.sky.exception.EditDishException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.utils.RedisDeleteKeysUtil;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetMealDishMapper setMealDishMapper;
    @Autowired
    private SetMealMapper setMealMapper;
    //缓存清理工具
    @Autowired
    private RedisDeleteKeysUtil redisDeleteKeysUtil;
    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int saveWithFlavor(DishDTO dishDTO) {
        //新增菜品 (dish中的value)
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);
        Long insertID = dish.getId();
        if(insertID==null){
            return 0;
        }
        //新增菜品口味 (dishFlavor中的value)
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null && !flavors.isEmpty()){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(insertID);
            });
            int result = dishFlavorMapper.insertFlavor(flavors);
            if(result==StatusConstant.RETURN0){
                return 0;
            }
        }
        return StatusConstant.RETURN1;
    }
    /**
     * 分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> data = dishMapper.pageQuery(dishPageQueryDTO);
        //总记录数
        long total = data.getTotal();
        //列表
        List<DishVO> list = data.getResult();
        //总记录数
        return new PageResult(total, list);
    }
    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getListByCategoryId(Long categoryId) {
        return dishMapper.getListByCategoryId(categoryId);
    }
    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatch(List<Long> ids) {
        //先查询包含的分类的id
        List<Long> categoryIds = dishMapper.getCategoryIdsByDishIds(ids);

        {
            //删除菜品表中的数据
            //删除菜品口味表中的关联数据
            List<String> namesByIdsResult = dishMapper.getStatusNamesByIds(ids, StatusConstant.ENABLE);
            if (namesByIdsResult != null && !namesByIdsResult.isEmpty()) {
                //提示异常信息
                throw new DeleteDishException(MessageConstant.DISH_ON_SALE + "[" + String.join(",", namesByIdsResult) + "]");
            }


            //判断--当前菜品是否与套餐关联
            List<Long> dishIdsBySetMealIdResult = setMealDishMapper.getDishIdsBySetMealId(ids);
            if (dishIdsBySetMealIdResult != null && !dishIdsBySetMealIdResult.isEmpty()) {
                // TODO 查询套餐名称（这里的查询套餐名称可能有问题）
                List<String> setMealNameById = setMealMapper.getSetMealNameById(dishIdsBySetMealIdResult);
                //提示异常信息
                throw new DeleteDishException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL + "[" + String.join(",", setMealNameById) + "]");
            }


            //删除菜品表中的数据(需要返回值确定)
            int deleteDishResult = dishMapper.deleteBatch(ids);
            if (deleteDishResult == StatusConstant.RETURN0) {
                throw new DeleteDishException(MessageConstant.FAIL_TO_DELETE);
            }
            //删除菜品口味表中的关联数据
            dishFlavorMapper.deleteByDishFlavorIds(ids);
        }

        //删除缓存数据
        redisDeleteKeysUtil.deleteDishKeys(categoryIds);
    }
    /**
     * 根据id查询菜品数据
     * @param {id}
     * @return
     */
    @Override
    public DishVO getDishVOById(Long id) {
        //查询菜品信息
        DishVO dishVOById = dishMapper.getDishVOById(id);
        //查询菜品关联的口味信息
        List<DishFlavor> flavors = dishFlavorMapper.getFlavorsByDishId(id);
//        二合一
        dishVOById.setFlavors(flavors);
        return dishVOById;
    }
    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void EditDish(DishDTO dishDTO) {
        //先修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        int result = dishMapper.EditDish(dish);
        if(result==StatusConstant.RETURN0){
            throw new EditDishException(MessageConstant.FAIL_TO_UPDATE);
        }
        //修改菜品关联口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null && !flavors.isEmpty()){
            //删除原有的口味数据
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(dishDTO.getId());
            int deleteByDishFlavorIdsResult = dishFlavorMapper.deleteByDishFlavorIds(dishIds);
            if(deleteByDishFlavorIdsResult==StatusConstant.RETURN0){
                throw new BaseException(MessageConstant.FAIL_TO_DELETE_FLAVORS);
            }
            //给予id值
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });
            //新增新的口味数据
            int insertFlavorResult = dishFlavorMapper.insertFlavor(flavors);
            if(insertFlavorResult==StatusConstant.RETURN0){
                throw new BaseException(MessageConstant.FAIL_INSERT_FLAVORS);
            }
        }
        //清楚缓存
        redisDeleteKeysUtil.deleteDishKey(dishDTO.getCategoryId());
    }
    /**
     * 菜品起售停售
     * @PathVariable status
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        int result = dishMapper.EditDish(dish);
        if(result==StatusConstant.RETURN0){
            throw new EditDishException(MessageConstant.FAIL_TO_UPDATE);
        }
        //清除缓存!
        List<Long> ids = new ArrayList<>();
        ids.add(dish.getId());
        //这里要查询获取数据库的后缀
        redisDeleteKeysUtil.deleteDishKeys(dishMapper.getCategoryIdsByDishIds(ids));
    }
    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //查询菜品数据
        List<DishVO> dishVOList = dishMapper.ParamQueryDishVO(dish);
        // TODO 优化sql，避免使用for循环 使用Map集合减少线程池的连接次数 优化性能
        //查询口味数据
        List<Long> dishIds = dishVOList
                .stream()
                .map(DishVO::getId)
                .collect(Collectors.toList());
        List<DishFlavor> flavors = dishFlavorMapper.getFlavorsByDishIds(dishIds);

        //TODO重点业务逻辑！！
        Map<Long, List<DishFlavor>> map = flavors.stream()
                .collect(Collectors.groupingBy(DishFlavor::getDishId));



        //封装口味数据
        if(CollectionUtils.isNotEmpty(dishVOList)){
            dishVOList.forEach(dishVO -> {
                dishVO.setFlavors(map.get(dishVO.getId()));
            });
        }
        return dishVOList;
    }
}